package com.service.yk.oktttpdemo.util;

import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;

/**
 * @author wangyongkun
 * @Description: 全局获取 okhttp实例工具类
 * @Date: 2020/4/2 15:00
 */
@Slf4j
public class OkHttpUtil {
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    public static final Callback callBack = new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            e.printStackTrace();
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            if (response.isSuccessful()) {
                System.out.println("success ...");
            } else {
                throw new IOException("Unexpected code " + response);
            }
        }

    };

    private OkHttpUtil() {
    }
    private static OkHttpClient okHttpClient = null;
    public static OkHttpClient getOkHttpInstance() {
        if (okHttpClient == null) {
            synchronized (OkHttpUtil.class) {
                okHttpClient = new OkHttpClient();
            }
        }
        return okHttpClient;
    }

    public static String doGet(String url) {
        OkHttpClient okHttpClient = getOkHttpInstance();
        Request request = new Request.Builder().url(url).build();
        try {
            log.info("doGet请求: {}", request);
            Response response = okHttpClient.newCall(request).execute();
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void asyncDoPost(String url, String json) {
        try {
            getOkHttpInstance().newCall(buildRequest(url, json)).enqueue(callBack);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String syncDoPost(String url, String json) {

        try {
            Response response = getOkHttpInstance().newCall(buildRequest(url, json)).execute();
            if (response != null) {
                return response.body().string();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static Request buildRequest(String url, String json) {
        Request.Builder requestBuilder = new Request.Builder().url(url);
        MediaType mediaType = JSON;
        if (json == null) {
            json = "{}";
        }
        return requestBuilder.post(RequestBody.create(mediaType, json)).build();
    }

}
